12. C++ Functions

Functions: Python vs C++

In both Python and C++, functions have the same role; functions group statements together to perform some task. Functions help you avoid copying and pasting the same code over and over again.

The syntax for writing functions is slightly different for mainly three reasons:

  1. Python detects the end of a code line based on seeing a carriage return and new line feed. C++ uses a semi-colon for the same purpose.
  2. Python uses indentation to group code statements together, but C++ uses curly braces.
  3. Python is dynamically typed while C++ is statically typed. Much like how you declared variables, you need to declare your functions.

Let's start off with a simple function and compare the Python and C++ code side-by-side.

This function takes in a velocity and time. These are multiplied together to calculate a distance. Besides the differences in syntax, pay special attention to:

  • the function declaration
  • variable declarations
  • what code goes inside main() and what code goes outside of main

Dissecting the Code

So the C++ code looks much longer than the Python code because the C++ has some extra parts. You are going to dissect this code piece by piece.

The code starts off with

#include <iostream>

That is importing the iostream part of the C++ Standard Library. You need that line of code in order to use cout.

After importing the necessary libraries, you see a function declaration.

float distance(float velocity, float time_elapsed); 

That line of code informs your C++ program that there is a function called distance. The function accepts two float variables and returns a float. The first float variable is called velocity and the second float variable is called time_elapsed.

Then comes the main function. All C++ programs require a main() function that returns a zero. The main() function calls the distance function and outputs the results to the terminal.

int main() {

    std::cout << distance(5, 4) << std::endl;
    std::cout << distance(12.1, 7.9) << std::endl;

    return 0;
}

and finally, you have the function definition

float distance(float velocity, float time_elapsed) {
    return velocity * time_elapsed;
}

You have seen the main() function before, so this isn't the first time you have seen how functions work in C++. Notice how the main function and the distance function have very similar syntax. The only difference is that the main function does not accept any arguments and returns an integer of value zero; on the other hand, the distance function accepts two floats and returns a float.

You also don't make a separate declaration for the main function. On the next page, you'll get more practice with understanding functions and writing functions in C++.